package com.example.peibei.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.dingtao.common.bean.Dynamic;
import com.dingtao.common.bean.GetComment;
import com.dingtao.common.bean.RefreshResult;
import com.dingtao.common.bean.SquareComment;
import com.dingtao.common.bean.SquareDetailTwo;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.DateUtils;
import com.dingtao.common.util.GlideUtils;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.service.presenter.AddSquareCommentPresenter;
import com.example.peibei.service.presenter.CommentFollowPresenter;
import com.example.peibei.service.presenter.FollowPresenter;
import com.example.peibei.service.presenter.FollowSquareDetailPresenter;
import com.example.peibei.service.presenter.FollowUserPresenter;
import com.example.peibei.service.presenter.GetSquareComentListPresenter;
import com.example.peibei.service.presenter.SquareDetailTwoPresenter;
import com.example.peibei.ui.utils.SoftKeyBoardListener;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.dingtao.common.util.DateUtils.DATE_PATTERN;

public class SquareDetailActivityTwo extends WDActivity {
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.ll_imgs)
    LinearLayout ll_imgs;
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.iv_img_one)
    ImageView imgOne;
    @BindView(R.id.iv_img_two)
    ImageView imgTwo;
    @BindView(R.id.iv_img_three)
    ImageView imgThree;
    @BindView(R.id.ll_no_follow)
    LinearLayout ll_no_follow;
    @BindView(R.id.ll_followed)
    LinearLayout ll_followed;
    @BindView(R.id.commentList)
    RecyclerView commentList;
    @BindView(R.id.zan)
    ImageView zan;
    @BindView(R.id.zan_tv)
    TextView zan_tv;
    @BindView(R.id.zan_ly)
    View zan_ly;
    @BindView(R.id.llContent)
    View llContent;
    @BindView(R.id.et_content)
    EditText mEtContent;
    @BindView(R.id.view_keybord)
    View view_keybord;
    @BindView(R.id.scroll_view)
    View scroll_view;
    @BindView(R.id.com_num)
    TextView com_num;

    private SPUtils spUtils;
    private String token;
    private FollowPresenter followPresenter;
    private FollowSquareDetailPresenter giveUpPresenter;
    private FollowUserPresenter followUserPresenter;
    GetSquareComentListPresenter comentListPresenter;
    private String subjectId;
    List<GetComment> list = new ArrayList<>();
    QuickAdapter quickAdapter = new QuickAdapter();
    private InputMethodManager mInputManager;
    AddSquareCommentPresenter dynamicComPresenter;
    private CommentFollowPresenter commentFollowPresenter;
    private int follow;
    private String dynamicId;
    private String mid;
    private SquareDetailTwoPresenter dynamicDetailTwoPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_square_detail_two;
    }

    @Override
    protected void initView() {
        mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        subjectId = bundle.getString("subjectId");
        spUtils = new SPUtils(SquareDetailActivityTwo.this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        dynamicDetailTwoPresenter = new SquareDetailTwoPresenter(new DynamicDetailCall());
        dynamicDetailTwoPresenter.reqeust("Bearer " + token, subjectId);
        followPresenter = new FollowPresenter(new FollowCall());
        giveUpPresenter = new FollowSquareDetailPresenter(new FollowCall());
        dynamicComPresenter = new AddSquareCommentPresenter(new CommentCall());
        followUserPresenter = new FollowUserPresenter(new FollowUserCall());
        commentFollowPresenter = new CommentFollowPresenter(new DianzanCall());
        comentListPresenter = new GetSquareComentListPresenter(new GetCommentListCall());
        ll_followed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                followUserPresenter.reqeust(0, "Bearer " + token, mid);
                ll_followed.setVisibility(View.GONE);
                ll_no_follow.setVisibility(View.VISIBLE);

            }
        });
        ll_no_follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                followUserPresenter.reqeust(1, "Bearer " + token, mid);
                ll_followed.setVisibility(View.VISIBLE);
                ll_no_follow.setVisibility(View.GONE);
            }
        });
        zan_ly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zan();
            }
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        commentList.setLayoutManager(linearLayoutManager);
        commentList.setAdapter(quickAdapter);

        initEditHight();
        mEtContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    dynamicComPresenter.reqeust("Bearer " + token, mEtContent.getText().toString(), subjectId);
                    mEtContent.setText("");
                    mInputManager.hideSoftInputFromWindow(mEtContent.getWindowToken(), 0);
                    mEtContent.clearFocus();
                }
                return false;
            }
        });
        mEtContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    lockContentHeight();//显示软件盘时，锁定内容高度，防止跳闪。

                    showSoftInput();


                    //软件盘显示后，释放内容高度
                    mEtContent.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            unlockContentHeightDelayed();
                        }
                    }, 200L);
                }
                return false;
            }
        });
        //点击空白区域关闭键盘
        scroll_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mInputManager.hideSoftInputFromWindow(mEtContent.getWindowToken(), 0);
                mEtContent.clearFocus();
                return false;
            }
        });
    }

    public void showSoftInput() {
        mEtContent.requestFocus();
        mEtContent.post(new Runnable() {
            @Override
            public void run() {
                mInputManager.showSoftInput(mEtContent, 0);
            }
        });
    }

    /**
     * 锁定内容高度，防止跳闪
     */
    private void lockContentHeight() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) llContent.getLayoutParams();
        params.height = llContent.getHeight();
        params.weight = 0.0F;
    }

    /**
     * 释放被锁定的内容高度
     */
    public void unlockContentHeightDelayed() {
        mEtContent.postDelayed(new Runnable() {
            @Override
            public void run() {
                ((LinearLayout.LayoutParams) llContent.getLayoutParams()).weight = 1.0F;
            }
        }, 200L);
    }

    /**
     * 使键盘能够弹起
     */
    private void initEditHight() {
        //监听软键盘弹出，并获取软键盘高度
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                //软键盘弹起事件  并给View设置高度
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view_keybord.getLayoutParams();
                layoutParams.height = height;
                view_keybord.setLayoutParams(layoutParams);
            }

            @Override
            public void keyBoardHide(int height) {
                //软键盘隐藏事件  并给View设置高度为0
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view_keybord.getLayoutParams();
                layoutParams.height = 0;
                view_keybord.setLayoutParams(layoutParams);
            }
        });

        quickAdapter.addChildClickViewIds(R.id.zan_ly);
        quickAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.zan_ly) {
//                    SquareComment.RecordsDTO item = (SquareComment.RecordsDTO) adapter.getData().get(position);
//                    int follow;
//                    int circleId = item.getId();
//                    boolean dianzan = item.isDianzan();
//                    if (dianzan) {
//                        follow = 0;
//                    } else {
//                        follow = 1;
//                    }
//                    commentFollowPresenter.reqeust(follow, "Bearer " + token, circleId);
                } else if (view.getId() == R.id.iv_head) {
                    SquareComment.RecordsDTO order = (SquareComment.RecordsDTO) adapter.getData().get(position);
                    Bundle bundle = new Bundle();
                    bundle.putString("mid", order.getId() + "");
                    intent(PersonInfoActivityTwo.class, bundle);
                }
            }
        });
    }

    private void zan() {
        giveUpPresenter.reqeust(follow, "Bearer " + token, subjectId);
    }

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    private void setOrderDetail(Dynamic.RecordsDTO data) {
        tv_name.setText(data.getMember().getNickName());
        tv_address.setText("来自" + data.getMember().getArea());
//        Glide.with(DynamicDetailActivityTwo.this).load(data.getMember().getImgUrl()).into(iv_head);
        Glide.with(SquareDetailActivityTwo.this).load(data.getMember().getImgUrl()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv_head);
        tv_content.setText(data.getTitle());
        List<Dynamic.RecordsDTO.ItemDTO> items = data.getItem();
        if (items.size() > 0) {
            ll_imgs.setVisibility(View.VISIBLE);
            if (items.get(0) != null && !items.get(0).getUrl().equals("")) {
//                Glide.with(this).load(items.get(0).getUrl()).into(imgOne);
                GlideUtils.loadImgTwo(this, items.get(0).getUrl(), 30, imgOne);
            }
            if (items.size() > 1 && items.get(1) != null && !items.get(1).getUrl().equals("")) {
//                Glide.with(this).load(items.get(1)).into(imgTwo);
                GlideUtils.loadImgTwo(this, items.get(1).getUrl(), 30, imgTwo);
            }
            if (items.size() > 2 && items.get(2) != null && !items.get(2).getUrl().equals("")) {
//                Glide.with(this).load(items.get(2).getUrl()).into(imgThree);
                GlideUtils.loadImgTwo(this, items.get(2).getUrl(), 30, imgThree);
            }
        } else {
            ll_imgs.setVisibility(View.GONE);
        }
        imgOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        imgTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }

    @OnClick(R.id.iv_head)
    public void toPersonInfo() {
        Bundle bundle = new Bundle();
        bundle.putString("mid", mid);
        intent(PersonInfoActivityTwo.class, bundle);
    }

    @Override
    protected void destoryData() {

    }

    class FollowCall implements DataCall<Dynamic> {

        @Override
        public void success(Dynamic data, Object... args) {
            dynamicDetailTwoPresenter.reqeust("Bearer " + token, subjectId);
        }

        @Override
        public void fail(ApiException e, Object... args) {
            EventBus.getDefault().post(RefreshResult.getInstance(true, true));
        }
    }

    String headUrl;

    class DynamicDetailCall implements DataCall<SquareDetailTwo> {

        @Override
        public void success(SquareDetailTwo data, Object... args) {
            tv_name.setText(data.getNickname());
            headUrl = data.getMemberUrl();
//            Glide.with(DynamicDetailActivityTwo.this).load(data.getMember().getImgUrl()).into(iv_head);
            Glide.with(SquareDetailActivityTwo.this).load(data.getMemberUrl()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv_head);
            tv_content.setText(data.getContent());
            if (!data.isFollow()) {
                follow = 0;
                zan.setImageResource(R.mipmap.zan_img);
            } else {
                follow = 1;
                zan.setImageResource(R.mipmap.zan_yellow);
            }
            dynamicId = data.getId();
            mid = data.getMid();
            comentListPresenter.reqeust(true, "Bearer " + token, subjectId);
            Log.i("answer", "点赞数量：" + data.getFollowerCount());
            if (data.getFollowerCount() > 0) {
                zan_tv.setText(data.getFollowerCount() + "");
            } else {
                zan_tv.setText("点赞");
            }
            List<String> imgs = data.getImgUrls();
            if (imgs.size() > 0) {
                ll_imgs.setVisibility(View.VISIBLE);
                if (imgs.get(0) != null && !imgs.get(0).equals("")) {
                    GlideUtils.loadImgTwo(SquareDetailActivityTwo.this, imgs.get(0), 30, imgOne);
                }
                if (imgs.size() > 1 && imgs.get(1) != null && !imgs.get(1).equals("")) {
                    GlideUtils.loadImgTwo(SquareDetailActivityTwo.this, imgs.get(1), 30, imgTwo);
                }
                if (imgs.size() > 2 && imgs.get(2) != null && !imgs.get(2).equals("")) {
                    GlideUtils.loadImgTwo(SquareDetailActivityTwo.this, imgs.get(2), 30, imgThree);
                }
            } else {
                ll_imgs.setVisibility(View.GONE);
            }
            imgOne.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            imgTwo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }

        @Override
        public void fail(ApiException e, Object... args) {

        }
    }

    class FollowUserCall implements DataCall<Dynamic> {

        @Override
        public void success(Dynamic data, Object... args) {
            //还需要刷新处理
            dynamicDetailTwoPresenter.reqeust("Bearer " + token, subjectId);
        }

        @Override
        public void fail(ApiException e, Object... args) {

        }
    }

    class DianzanCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            //还需要刷新处理
            comentListPresenter.reqeust(true, "Bearer " + token, subjectId);
        }

        @Override
        public void fail(ApiException e, Object... args) {
//            EventBus.getDefault().post(RefreshResult.getInstance(true, true));
        }
    }


    class CommentCall implements DataCall<Dynamic> {

        @Override
        public void success(Dynamic data, Object... args) {
            //还需要刷新处理
            comentListPresenter.reqeust(true, "Bearer " + token, subjectId);
            UIUtils.showToastSafe("评论成功");
        }

        @Override
        public void fail(ApiException e, Object... args) {
//            EventBus.getDefault().post(RefreshResult.getInstance(true, true));
        }
    }

    class GetCommentListCall implements DataCall<SquareComment> {

        @Override
        public void success(SquareComment data, Object... args) {
            //添加列表并刷新
            if (comentListPresenter.getPage() == 1) {
                list.clear();
            }
            quickAdapter.setNewInstance(data.getRecords());
            quickAdapter.notifyDataSetChanged();
            com_num.setText(String.valueOf(data.getTotal()));
        }

        @Override
        public void fail(ApiException e, Object... args) {
            Log.e("eeeeeee", e.toString());
        }
    }


    public class QuickAdapter extends BaseQuickAdapter<SquareComment.RecordsDTO, BaseViewHolder> {

        public QuickAdapter() {
            super(R.layout.comment_list_item_layout);
        }

        @Override
        protected void convert(BaseViewHolder viewHolder, final SquareComment.RecordsDTO item) {
            viewHolder.setText(R.id.commentMember, item.getComUserName())
                    .setText(R.id.message, item.getContent())
                    .setText(R.id.addTime, item.getCreateTime());
            View rply_ly = viewHolder.getView(R.id.rply_ly);
            rply_ly.setVisibility(View.GONE);

//            if (TextUtils.isEmpty(item.getReply())) {
//                rply_ly.setVisibility(View.GONE);
//            } else {
//                rply_ly.setVisibility(View.VISIBLE);
//                viewHolder.setText(R.id.reply_name, item.getAddTime())
//                        .setText(R.id.reply, item.getReply())
//                        .setText(R.id.addTime, item.getAddTime());
//            }
            ImageView head = viewHolder.getView(R.id.iv_head);
            ImageView iv_head_small = viewHolder.getView(R.id.iv_head_small);
            ImageView zan = viewHolder.getView(R.id.zan);
            TextView zan_tv = viewHolder.getView(R.id.zan_tv);
            Glide.with(SquareDetailActivityTwo.this).load(item.getImage()).into(head);
            Glide.with(SquareDetailActivityTwo.this).load(headUrl).into(iv_head_small);

//            if (!item.isDianzan()) {
//                zan.setImageResource(R.mipmap.zan_img);
//                zan_tv.setText("点赞");
//                zan_tv.setTextColor(Color.parseColor("#ff6a6b6e"));
//            } else {
//                zan.setImageResource(R.mipmap.zan_yellow);
//                zan_tv.setText(item.getFollow());
//                zan_tv.setTextColor(Color.parseColor("#9D9CD8"));
//            }
        }
    }
}
